package com.atguigu.srb.sms.service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.atguigu.common.exception.Assert;
import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.sms.util.SmsProperties;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class SmsServiceImpl implements  SmsService{
    @Override
    public void send(String mobile, String templateCode, Map<String, Object> param) {
        DefaultProfile profile = DefaultProfile.getProfile(SmsProperties.REGION_Id,
                SmsProperties.KEY_ID,
                SmsProperties.KEY_SECRET);
        /** use STS Token
         DefaultProfile profile = DefaultProfile.getProfile(
         "<your-region-id>",           // The region ID
         "<your-access-key-id>",       // The AccessKey ID of the RAM account
         "<your-access-key-secret>",   // The AccessKey Secret of the RAM account
         "<your-sts-token>");          // STS Token
         **/

        IAcsClient client = new DefaultAcsClient(profile);

        Gson gson = new Gson();
        String json = gson.toJson(param);
        SendSmsRequest request = new SendSmsRequest();
        request.setSignName(SmsProperties.SIGN_NAME);
        request.setTemplateCode(templateCode);
        request.setTemplateParam(json);
        request.setPhoneNumbers(mobile);

        try {
            // 使用客户端对象携带请求参数向远程阿里云服务器发起远程调用，并得到相应结果
            SendSmsResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));

            // 得到响应结果的json形式
            String gsonData = new Gson().toJson(response);
            HashMap<String, String> resultMap = gson.fromJson(gsonData, HashMap.class); // 将json转化为Hashmap对象
            String code = resultMap.get("code");
            resultMap.get("message");

            Assert.notEquals("isv.BUSINESS_LIMIT_CONTROL", code, ResponseEnum.ALIYUN_SMS_LIMIT_CONTROL_ERROR);
            Assert.equals("OK", code, ResponseEnum.ALIYUN_SMS_ERROR);
        } catch (ServerException e) {
            // 打印错误信息
            log.error("阿里云短信发送sdk调用失败: " + e.getErrCode() + ", " + e.getErrMsg());
            // 向前端反应信息
            throw new BusinessException(ResponseEnum.ALIYUN_SMS_ERROR, e);
        } catch (ClientException e) {
            // 打印错误信息
            log.error("阿里云短信发送sdk调用失败: " + e.getErrCode() + ", " + e.getErrMsg());
            // 向前端反应信息
            throw new BusinessException(ResponseEnum.ALIYUN_SMS_ERROR, e);
        }
    }
}
